package distributelock

import (
	"context"
	"fmt"
	"lnzw/engine/etcd"

	c "go.etcd.io/etcd/clientv3"
)

type etcdLock struct {
}

func (lock *etcdLock) Init() error {
	if err := etcd.Setup(); err != nil {
		return err
	}
	return nil
}

func (lock *etcdLock) Lock(key string) (bool, error) {
	leaseRsp, err := etcd.GlobalEtcd.Lease.Grant(context.Background(), 5000)
	if err != nil {
		return false, err
	}
	keymapping := fmt.Sprintf("%s%s", lock_prefix, key)
	leaseId := leaseRsp.ID
	txnRsp, err := etcd.GlobalEtcd.
		Txn(context.Background()).
		If(c.Compare(c.Version(keymapping), "=", 0)).
		Then(c.OpPut(keymapping, "1", c.WithLease(leaseId))).
		Commit()
	if err != nil {
		return false, err
	}
	return txnRsp.Succeeded, nil
}

func (lock *etcdLock) UnLock(key string) (bool, error) {
	keymapping := fmt.Sprintf("%s%s", lock_prefix, key)
	rsp, err := etcd.GlobalEtcd.Delete(context.Background(), keymapping)
	return rsp.Deleted > 0, err
}
